var EARTH_RADIUS = 6378137.0; //单位M :米
var PI = Math.PI;
 
function getRad(d) {
  return d * PI / 180.0;
}
 
/**
 * caculate the great circle distance
 * @param {Object} lat1 纬度
 * @param {Object} lng1 经度
 * @param {Object} lat2
 * @param {Object} lng2
 */
export function getFlatternDistance(lat1,lng1,lat2,lng2){
    var f = getRad((lat1 + lat2)/2);
    var g = getRad((lat1 - lat2)/2);
    var l = getRad((lng1 - lng2)/2);
    
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);
    
    var s,c,w,r,d,h1,h2;
    var a = EARTH_RADIUS;
    var fl = 1/298.257;
    
    sg = sg*sg;
    sl = sl*sl;
    sf = sf*sf;
    
    s = sg*(1-sl) + (1-sf)*sl;
    c = (1-sg)*(1-sl) + sf*sl;
    
    w = Math.atan(Math.sqrt(s/c));
    r = Math.sqrt(s*c)/w;
    d = 2*w*a;
    h1 = (3*r -1)/2/c;
    h2 = (3*r +1)/2/s;
    
    return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
}
// getFlatternDistance(22.576979, 114.065712, 22.574034, 114.065739);


// 确保已经加载了百度地图API
export function calculateDistance(point1, point2) {
  const { lat: lat1, lng: lng1 } = point1;
  const { lat: lat2, lng: lng2 } = point2;
  const map = new BMap.Map("container"); // 用于转换坐标，但不实际显示地图
  const convertor = new BMap.Convertor();

  const pointA = new BMap.Point(lng1, lat1);
  const pointB = new BMap.Point(lng2, lat2);

  // 由于输入可能是GPS坐标，需要转换为百度坐标
  convertor.translate([pointA, pointB], 1, 5, function(data) {
      if (data.status === 0) {
          const translatedPoints = data.points;
          const pointX = translatedPoints[0].point;
          const pointY = translatedPoints[1].point;

          const distance = map.getDistance(pointX, pointY);
          console.log('Distance (in meters):', distance);
      } else {
          console.error('Translation error:', data.status);
      }
  });
}

// 使用示例
// calculateDistance({ lat: 39.984060, lng: 116.450285 }, // 北京天安门
//                { lat: 40.712832, lng: -74.006058 }); // 纽约自由女神像